package data

import (
	"context"
	productV1 "shop-demo/api/product/v1"
	"shop-demo/app/shop/bff/internal/biz"
)

type productRepo struct {
	data *Data
}

func NewProductRepo(data *Data) biz.ProductRepo {
	return &productRepo{
		data: data,
	}
}

func (p *productRepo) CreateProduct(ctx context.Context, product *biz.Product) (*biz.Product, error) {
	reply, err := p.data.productClient.CreateProduct(ctx, &productV1.CreateProductReq{
		Name: product.Name,
		Num:  product.Num,
	})
	if err != nil {
		return nil, err
	}
	return &biz.Product{
		Id: reply.Id,
	}, nil
}

func (p *productRepo) UpdateProduct(ctx context.Context, product *biz.Product) (*biz.Product, error) {
	reply, err := p.data.productClient.UpdateProduct(ctx, &productV1.UpdateProductReq{
		Id:  product.Id,
		Num: product.Num,
	})
	if err != nil {
		return nil, err
	}
	return &biz.Product{
		Id:  reply.Id,
		Num: reply.Num,
	}, nil
}

func (p *productRepo) DeleteProduct(ctx context.Context, id int64) error {
	_, err := p.data.productClient.DeleteProduct(ctx, &productV1.DeleteProductReq{Id: id})
	return err
}

func (p *productRepo) GetProduct(ctx context.Context, id int64) (*biz.Product, error) {
	reply, err := p.data.productClient.GetProduct(ctx, &productV1.GetProductReq{Id: id})
	if err != nil {
		return nil, err
	}
	return &biz.Product{
		Id:   reply.Id,
		Name: reply.Name,
		Num:  reply.Num,
	}, nil
}

func (p *productRepo) ListProduct(ctx context.Context, pageNum int, pageSize int) ([]*biz.Product, error) {
	reply, err := p.data.productClient.ListProduct(ctx, &productV1.ListProductReq{
		PageNum:  int64(pageNum),
		PageSize: int64(pageSize),
	})
	if err != nil {
		return nil, err
	}
	result := make([]*biz.Product, 0, len(reply.Products))

	for _, product := range reply.Products {
		result = append(result, &biz.Product{
			Id:   product.Id,
			Name: product.Name,
			Num:  product.Num,
		})
	}
	return result, nil
}
